package com.zyz.friend.service.exam.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zyz.common.core.model.TableDataInfo;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.common.security.service.TokenService;
import com.zyz.friend.manager.ExamCacheManager;
import com.zyz.friend.manager.UserCacheManager;
import com.zyz.friend.mapper.exam.ExamMapper;
import com.zyz.friend.mapper.userexam.UserExamMapper;
import com.zyz.friend.model.exam.Exam;
import com.zyz.friend.model.exam.dto.ExamQueryDTO;
import com.zyz.friend.model.exam.dto.ExamRankDTO;
import com.zyz.friend.model.exam.vo.ExamRankVO;
import com.zyz.friend.model.exam.vo.ExamVO;
import com.zyz.friend.model.user.vo.UserVO;
import com.zyz.friend.service.exam.IExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ExamServiceImpl implements IExamService {


    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserExamMapper userExamMapper;

    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        // 使用pagehelper来自动帮我们处理分页功能（自动帮忙修改我们的sql语句，在后面拼接limit x,x）
        PageHelper.startPage(examQueryDTO.getPageNumber(), examQueryDTO.getPageSize());
        List<ExamVO> examVOList = examMapper.selectExamList(examQueryDTO);
        if (examVOList == null || examVOList.isEmpty()) {
            return TableDataInfo.empty();
        }
        // 通过pageInfo拿到符合分页查询到的数据，并通过getTotal拿到个数
        long total = new PageInfo<>(examVOList).getTotal();
        return TableDataInfo.success(examVOList, total);
    }

    @Override
    public TableDataInfo redisList(String token,ExamQueryDTO examDTO) {
        Long userId = tokenService.getUserId(token,secret);
        // 从redis中查询竞赛列表的数据
        Long total = examCacheManager.getListSize(examDTO.getType(),userId);
        List<ExamVO> examVOList = null;
        if (total == null || total <= 0) {
            // 从数据库中拿数据
            TableDataInfo list = list(examDTO);
            examVOList = (List<ExamVO>) list.getRows();
            total = new PageInfo<>(examVOList).getTotal();
            // 刷新redis中缓存
            examCacheManager.refreshCache(examDTO.getType(),userId);
        } else {
            examVOList = examCacheManager.getExamVOList(examDTO, userId);
            total = examCacheManager.getListSize(examDTO.getType(),userId);// 记得重新获取数量 以防redis中异常情况（的调用getExamVOList里面）
        }
        assembleExamVOList(examVOList,userId);
        return CollectionUtil.isEmpty(examVOList)?
                TableDataInfo.empty():TableDataInfo.success(examVOList, total);
    }

    @Override
    public String firstQuestion(Long examId) {
        // 从cache缓存中查询题目
        checkAndRefreshCache(examId);
        // 从缓存中查询该竞赛的第一道题目
        Long firstQuestionId = examCacheManager.getFirstQuestion(examId);
        return firstQuestionId.toString();
    }

    @Override
    public String preQuestion(Long examId, Long questionId) {
        checkAndRefreshCache(examId);
        // 从缓存中拿到questionId的下一题
        return examCacheManager.getPreQuestionId(examId,questionId).toString();
    }

    @Override
    public String nextQuestion(Long examId, Long questionId) {
        checkAndRefreshCache(examId);
        // 从缓存中拿到questionId的下一题
        return examCacheManager.getNextQuestionId(examId,questionId).toString();
    }

    @Override
    public TableDataInfo rankList(ExamRankDTO rankDTO) {
        Long examId = rankDTO.getExamId();
        // 从redis中查询竞赛列表的数据
        Long total = examCacheManager.getRankListSize(examId);
        List<ExamRankVO> examRankVOList = null;
        if (total == null || total <= 0) {
            // 使用pagehelper来自动帮我们处理分页功能（自动帮忙修改我们的sql语句，在后面拼接limit x,x）
            PageHelper.startPage(rankDTO.getPageNumber(), rankDTO.getPageSize());
            // 从数据库中拿数据
            examRankVOList = userExamMapper.selectExamRankList(examId);
            // 刷新redis中缓存
            examCacheManager.refreshRankCache(examId);
        } else {
            examRankVOList = examCacheManager.getExamRankList(rankDTO);
            total = examCacheManager.getRankListSize(examId);// 记得重新获取数量 以防redis中异常情况
        }
        assembleExamRankList(examRankVOList);
        return CollectionUtil.isEmpty(examRankVOList)?
                TableDataInfo.empty():TableDataInfo.success(examRankVOList, total);
    }

    @Override
    public TableDataInfo listByTime(ExamQueryDTO examQueryDTO) {
        LocalDateTime start = null;
        LocalDateTime end = null;
        // 构造查询wrapper
        LambdaQueryWrapper<Exam> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtil.isNotEmpty(examQueryDTO.getStartTime())) {
            start = LocalDateTime.parse(examQueryDTO.getStartTime());
            queryWrapper.ge(Exam::getCreateTime,start);
        }
        if (StringUtil.isNotEmpty(examQueryDTO.getEndTime())) {
            end = LocalDateTime.parse(examQueryDTO.getEndTime());
            queryWrapper.le(Exam::getCreateTime,end);
        }
        if (start != null && end != null && start.isAfter(end)) {
            log.error("查询竞赛开始时间不得大于结束时间");
            throw new ServiceException("查询竞赛开始时间不得大于结束时间");
        }
        queryWrapper.eq(Exam::getOverStatus,examQueryDTO.getType()).orderByDesc(Exam::getCreateTime);
        PageHelper.startPage(examQueryDTO.getPageNumber(), examQueryDTO.getPageSize());
        // 查询数据库
        List<Exam> exams = examMapper.selectList(queryWrapper);
        List<ExamVO> examVOList = new ArrayList<>();
        exams.forEach(exam -> {
            ExamVO examVO = BeanUtil.copyProperties(exam, ExamVO.class);
            examVOList.add(examVO);
        });
        long total = new PageInfo<>(examVOList).getTotal();
        return CollectionUtil.isEmpty(examVOList)?
                TableDataInfo.empty():TableDataInfo.success(examVOList, total);
    }

    private void assembleExamRankList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            Long userId = examRankVO.getUserId();
            UserVO userById = userCacheManager.getUserById(userId);
            examRankVO.setNickName(userById.getNickName());
        }
    }

    private void checkAndRefreshCache(Long examId) {
        Long CacheListSize = examCacheManager.getExamQuestionListSize(examId);
        if (CacheListSize == null || CacheListSize <= 0) {
            // 刷新cache缓存
            examCacheManager.refreshExamQuestionList(examId);
        }
    }

    private void assembleExamVOList(List<ExamVO> examVOList,Long userId) {
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }
}
